package leetcode.code0556;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int nextGreaterElement(int n) {
		// 1245873
		// 1247358
		List<Integer> list = new ArrayList<>();
		while (n > 0) {
			list.add(n % 10);
			n /= 10;
		}
		Integer[] nums = list.toArray(new Integer[] {});
		int len = nums.length;
		int l = 0, r = len, L = -1;
		while (l < len && l < r) {
			int num = nums[l];
			for (int i = l + 1; i < r; i++) {
				if (nums[i] < num) {
					r = i;
					L = l;
					break;
				}
			}
			l++;
		}
		if (L == -1) {
			return -1;
		}
		this.swap(nums, L, r);
		this.sort(nums, 0, r);
		long ans = this.ans(nums);
		return ans > Integer.MAX_VALUE ? -1 : (int) ans;
	}

	private long ans(Integer[] nums) {
		long ans = 0;
		for (int i = nums.length - 1; i >= 0; i--) {
			ans = ans * 10 + nums[i];
		}
		return ans;
	}

	private void sort(Integer[] nums, int l, int r) {
		for (int i = l; i < r; i++) {
			for (int j = i + 1; j < r; j++) {
				if (nums[j] > nums[i]) {
					this.swap(nums, i, j);
				}
			}
		}
	}

	private void swap(Integer[] nums, int l, int r) {
		int tmp = nums[l];
		nums[l] = nums[r];
		nums[r] = tmp;
	}

	@Override
	public void debug4() {
		H.compare(230412, this.nextGreaterElement(230241));
		H.compare(1247358, this.nextGreaterElement(1245873));
		H.compare(-1, this.nextGreaterElement(999));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		System.out.println(Integer.MAX_VALUE);
	}

}
